package com.stylefeng.guns.rest.modular.wz.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.rest.common.persistence.dao.WzUserSmsMapper;
import com.stylefeng.guns.rest.common.persistence.model.WzUserSms;
import com.stylefeng.guns.rest.common.util.AliyunSmsUtil;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.EnWzUserSms;
import com.stylefeng.guns.rest.modular.wz.service.IWzCommonService;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import com.stylefeng.guns.rest.modular.wz.util.wz.IDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 公共模块实现
 */
@Service
public class WzCommonServiceImpl implements IWzCommonService{

    @Autowired
    private WzUserSmsMapper wzUserSmsMapper;

    /**
     * 短信接口并返回结果
     */
    @Transactional
    public Res sendSms(int type,String tel,String temolateCode,int smsType) throws Exception{
        //发送短信
        String code = IDUtil.random(4);
        SendSmsResponse response = AliyunSmsUtil.sendSms(tel,code, temolateCode);
        if(response != null){
            if(response.getCode().equals("OK")){
                //失效前面未使用的验证码
                EntityWrapper<WzUserSms> ew = new EntityWrapper<>();
                List<WzUserSms> wzUserSmsList = wzUserSmsMapper.selectList(ew.where("tel="+tel+"").and("sms_type="+smsType+"").and("status="+ EnWzUserSms.STATUS_AVAILABLE.getIndex()+""));
                for(WzUserSms s :wzUserSmsList){
                    s.setStatus(0);
                    int rr = wzUserSmsMapper.updateById(s);
                }
                //新建短信记录
                WzUserSms wzUserSms = new WzUserSms();
                wzUserSms.setType(type);
                wzUserSms.setSmsType(smsType);
                wzUserSms.setTel(tel);
                wzUserSms.setVaildCode(code);
                wzUserSms.setVaildTimes(10);
                wzUserSms.setStartTime(new Date());
                wzUserSms.setStatus(1);
                wzUserSms.setEndTime(DateUtil.addMinute(wzUserSms.getStartTime(), wzUserSms.getVaildTimes()));
                int r = wzUserSmsMapper.insert(wzUserSms);
                if(r > 0){
                    return Res.success();
                }
            }else if(response.getCode().equals("isv.BUSINESS_LIMIT_CONTROL")){
                return Res.fail("请求频繁！");
            }
            return Res.fail("短信发送失败！");
        }
        return Res.success("短信发送失败！");
    }
}
